-module(wordservice_app).

-behaviour(application).

%% Application callbacks
-export([start/2, stop/1]).

%% ===================================================================
%% Application callbacks
%% ===================================================================

start(_StartType, _StartArgs) ->
    {ok, MysqlHost} = application:get_env(wordservice, mysql_host),
    {ok, MysqlPort} = application:get_env(wordservice, mysql_port),
    {ok, MysqlUser} = application:get_env(wordservice, mysql_user),
    {ok, MysqlDb} = application:get_env(wordservice, mysql_db),
    {ok, MysqlPass} = application:get_env(wordservice, mysql_pass),
    {ok, MysqlPoolSize} = application:get_env(wordservice, mysql_pool_size),
    {ok, ListenPort} = application:get_env(wordservice, listen_port),
    connect_db(['word_pool', MysqlPoolSize, MysqlUser, MysqlPass, MysqlHost, MysqlPort, MysqlDb]),
    mod_word:load_db_sensitive_word(),
    cowboy_listen(ListenPort),
    wordservice_sup:start_link().

cowboy_listen(ListenPort) ->
    Dispatch = cowboy_router:compile([
        {'_', [{'_', word_handler, []}]}
    ]),
    {ok, _} = cowboy:start_http(word_http_listener, 100, [{port, ListenPort}],
        [{env, [{dispatch, Dispatch}]}]
    ).


connect_db([PoolName, MysqlPoolSize, MysqlUser, MysqlPass, MysqlHost, MysqlPort, MysqlDb] = P) ->
    case emysql:add_pool(PoolName, MysqlPoolSize, MysqlUser, MysqlPass, MysqlHost, MysqlPort, MysqlDb, utf8) of
        ok ->
            ok;
        Err -> 
            lager:info("error connecting db: ~p, info: ~p", [Err, P]),
            timer:sleep(5000),
            exit
    end.

stop(_State) ->
    ok.
